package com.pktechan.api.service.impl;

import com.pktechan.api.base.BaseMapper;
import com.pktechan.api.base.BaseServiceImpl;
import com.pktechan.api.dao.MsgCodeMapper;
import com.pktechan.api.entity.MsgCode;
import com.pktechan.api.enumeration.YesOrNoEnum;
import com.pktechan.api.exception.CustomException;
import com.pktechan.api.service.MsgCodeService;
import com.pktechan.api.service.RedisService;
import com.pktechan.api.utils.DateUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import static com.pktechan.api.utils.RandomUtil.createR;

@Service("msgCodeService")
@Transactional
public class MsgCodeServiceImpl extends BaseServiceImpl<MsgCode> implements MsgCodeService {

    @Autowired
    private MsgCodeMapper msgCodeMapper;

    @Value("${send-msg.secret-id}")
    private String secretId;
    @Value("${send-msg.secret-key}")
    private String secretKey;
    @Value("${send-msg.endpoint}")
    private String endpoint;
    @Value("${send-msg.template-id}")
    private String templateId;
    @Value("${send-msg.sign}")
    private String sign;
    @Value("${send-msg.sms-sdk-app-id}")
    private String smsSdkAppId;
    @Autowired
    private RedisService redisService;

    /**
     * 由业务类实现
     *
     * @return
     */
    @Override
    public BaseMapper<MsgCode> getBaseMapper() {
        return msgCodeMapper;
    }

    /**
     * 发送手机验证码
     *
     * @param mobile
     * @return
     */
    @Override
    public MsgCode sendMessageCode(String mobile) {
        String mobile86 = "+86" + mobile;
        String code = createR(6);
        Credential cred = new Credential(secretId, secretKey);

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        SmsClient client = new SmsClient(cred, "", clientProfile);

        SendSmsRequest req = new SendSmsRequest();
        String[] phoneNumberSet1 = {};
        Set<String> phoneSet = new HashSet<>();
        phoneSet.add(mobile86);
        phoneNumberSet1 = phoneSet.toArray(phoneNumberSet1);

        req.setPhoneNumberSet(phoneNumberSet1);

        req.setTemplateID(templateId);
        req.setSign(sign);
        String[] templateParamSet1 = {};
        Set<String> templateParamSet = new HashSet<>();
        templateParamSet.add(code);
        templateParamSet1 = templateParamSet.toArray(templateParamSet1);
        req.setTemplateParamSet(templateParamSet1);

        req.setSmsSdkAppid(smsSdkAppId);


        try {
            SendSmsResponse resp = client.SendSms(req);
            MsgCode msgCode = new MsgCode();
            msgCode.setSerialNo(resp.getSendStatusSet()[0].getSerialNo());
            msgCode.setSendStatus(resp.getSendStatusSet()[0].getCode());
            msgCode.setSendMessage(resp.getSendStatusSet()[0].getMessage());
            msgCode.setSendRequestId(resp.getRequestId());
            msgCode.setCode(code);
            msgCode.setMobile(mobile);
            msgCode.setIsCheck(YesOrNoEnum.NO.getCode());
            Date createTime = new Date();
            msgCode.setCreateTime(createTime);
            msgCode.setExpireTime(DateUtil.addMinute(createTime, 5));
            msgCodeMapper.save(msgCode);
            //将验证码保存到redis中
            redisService.setMsgCode(mobile,code);

            return msgCode;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new CustomException("验证码发送失败");
        }
    }

    /**
     * 更改手机验证码状态
     * @param mobile
     * @param code
     */
    @Override
    public void updateMessageCode(String mobile, String code) {
        MsgCode msgCode = new MsgCode();
        msgCode.setMobile(mobile);
        msgCode.setCode(code);
        msgCode.setIsCheck(YesOrNoEnum.YES.getCode());
        msgCodeMapper.updateMessageCode(msgCode);
    }
}
